package com.myhome.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myhome.entity.Employee;
import com.myhome.entity.RespBean;
import com.myhome.entity.RespPageBean;
import com.myhome.mapper.EmployeeMapper;
import com.myhome.service.IEmployeeService;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.Format;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2021-09-04
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public RespPageBean getEmployeeWithPages(Integer currentPage, Integer size, Employee employee, LocalDate[] timeScope) {
        Page<Employee> page = new Page<>(currentPage, size);
        IPage employeeWithPages = employeeMapper.getEmployeeWithPages(page, employee, timeScope);
        return new RespPageBean(employeeWithPages.getTotal(), employeeWithPages.getRecords());
    }

    @Override
    public RespBean getMaxId() {
        List<Map<String, Object>> result = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));
        return RespBean.success("", String.format("%08d",Integer.parseInt(result.get(0).get("max(workID)").toString()) + 1));
    }

    @Override
    public RespBean addEmp(Employee employee) {
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        long allContract = beginContract.until(endContract, ChronoUnit.DAYS);
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        double v = Double.parseDouble(decimalFormat.format(allContract / 365.00));
        employee.setContractTerm(v);
        if (1 == employeeMapper.insert(employee)) {
            rabbitTemplate.convertAndSend("mail",employee);
            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    @Override
    public List<Employee> getEmployee(Integer id) {
        return employeeMapper.getEmployee(id);
    }
}
